package club.janna.netty.optimize;

import io.netty.bootstrap.Bootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;

import java.util.concurrent.ExecutionException;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * 客户端 - 挑战百万连接
 */
public class Client {

    /**
     * 端口开始地址
     */
    private final static int DEFAULT_START_PORT = 9000;
    /**
     * 连接多少个端口
     */
    private final static int DEFAULT_PORT_NUM = 100;

    /**
     * 每个端口连接多少次
     */
    private final static int DEFAULT_CONNECT_NUM = 50000;

    /**
     * 连接计数
     */
    private final static AtomicInteger count = new AtomicInteger(0);

    public static void main(String[] args) throws ExecutionException, InterruptedException {
        int startPort = DEFAULT_START_PORT;
        int portNum = DEFAULT_PORT_NUM;
        int connectNum = DEFAULT_CONNECT_NUM;
        String host = null;

        // 从命令行参数中读取配置
        if(args != null) {
            if(args.length >= 1) {
                if("help".equals(args[0])) {
                    System.out.println("java Client host [startPort [portNum [connectNum]]]\r\n" +
                            "\thost 要连接的服务器地址（必填）\r\n" +
                            "\tstartPort 开始的端口号（默认9000）\r\n" +
                            "\tportNum 要连接多少个端口（默认100）\r\n" +
                            "\tconnectNum 每个端口连接多少次（默认50000）\r\n");
                    System.exit(0);
                }
                host = args[0];
            }
            if(args.length >= 2)
                startPort = Integer.parseInt(args[1]);
            if(args.length >= 3)
                portNum = Integer.parseInt(args[2]);
            if(args.length >= 4)
                connectNum = Integer.parseInt(args[3]);
        } else {
            System.err.println("请在命令行参数中指定服务器ip");
            System.exit(-1);
        }

        Bootstrap bootstrap = new Bootstrap();
        bootstrap.group(new NioEventLoopGroup())
                .channel(NioSocketChannel.class)
                .handler(new ChannelInitializer<SocketChannel>() {
                    @Override
                    protected void initChannel(SocketChannel ch) throws Exception {

                    }
                });
        for (int j = 0; j < connectNum; j++) { // 每个端口n次
            for (int i = 0; i < portNum; i++) {
                final int port = startPort + i;
                ChannelFuture channelFuture = bootstrap.connect(host, port);
                channelFuture.addListener(future -> {
                    if(!future.isSuccess()) {
                        System.err.println("连接失败");
//                        System.exit(-2);
                    }
                });
            }
        }
    }
}
